<template>
    <view>
        <view
            style="
                width: 750rpx;
                position: fixed;
                z-index: 100;
                background: #fff;
            "
            :style="{
                height: systemInfo.statusBarHeight + 'px',
            }"
        ></view>
        <view
            class="slim_header d-flex a-center j-center"
            style="border-bottom: none"
            :style="{ top: systemInfo.statusBarHeight + 'px' }"
        >
            <view class="left_box" @tap="goBack">
                <image src="/static/center/back.png" class="back"></image>
            </view>
            <view class="title">我的头像</view>
            <view class="right_box">
                <!-- <image src="/static/center/dian.png" class="dian"></image> -->
            </view>
        </view>

        <view
            class="content"
            :style="{ top: `calc(100rpx + ${systemInfo.statusBarHeight}px)` }"
        >
            <view class="box">
                <image class="userhead" mode="widthFix" :src="userhead" />
                <view class="control d-flex d-c a-center j-center">
                    <view class="btn_main_r btn1" @tap="select">
                        <view class="text">更改头像</view>
                    </view>

                    <!-- <tm-button
                        class="btn btn1 w-center"
                        :width="710"
                        :height="80"
                        :shadow="-1"
                        :linear-color="['#64F1C5', '#29DBA3']"
                        linear="left"
                        :fontSize="32"
                        fontColor="#ffffff"
                        label="更改头像"
                        @tap="select"
                    ></tm-button> -->

                    <view class="btn_main_r_line btn2" @tap="SaveImg">
                        <view class="text" style="font-weight: 600;">保存图片</view>
                    </view>

                    <!-- <view
                        class="btn btn2 w-center d-flex a-center j-center"
                        @tap="SaveImg"
                        >保存图片</view
                    > -->
                </view>
            </view>
        </view>

        <!-- watermark="水印来了"
            :watermarkType="1" -->
        <cropper
            mode="free"
            :width="200"
            :height="200"
            :maxWidth="1024"
            :maxHeight="1024"
            :url="imgurl"
            @cancel="cancel"
            @ok="complete"
        ></cropper>
    </view>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import { onShow, onLoad } from "@dcloudio/uni-app";
import cropper from "@/components/cropper";
import { systemInfo as systemInfoStore } from "@/store/systemInfo";
import {
    uploadFile,
    downloadFile,
    saveImg,
    showLoading,
    closeLoading,
} from "@/utils/utils";
import { chooseImage } from "@/utils/utils";
const goBack = () => {
    uni.navigateBack();
};

const systemInfo = systemInfoStore();
const imgurl = ref("");
const userhead = ref("");

const complete = async (ev) => {
    console.log("complete");
    console.log("complete");
    console.log("complete");
    console.log(ev);
    const result = await uploadFile(ev.path).catch(()=>{
        uni.showToast({
            icon: "none",
            title: "上传图片失败",
        });
    })

    if(result){

        const index = result.lastIndexOf('.');
        const name = result.substring(0,index);
        const ext = result.substring(index,result.length);

        userhead.value = `${name}-big${ext}`;
        uni.$emit('userheadChange',result)
        setTimeout(()=>{
            closeLoading();
            imgurl.value = "";
        },500)
    }

};

const cancel = () => {
    imgurl.value = "";
};

let reqTimes = 0;
let tapLoading = false;

const SaveImg = async () => {
    if(tapLoading){
        return;
    }
    tapLoading = true;
    showLoading();
    const tempFilePath = await downloadFile(userhead.value).catch(() => {
        uni.showToast({
            icon: "none",
            title: "保存图片失败",
        });
        closeLoading();
        tapLoading = false;
    });
    if(!tempFilePath){
        closeLoading();
        tapLoading = false;
        return
    }

    const result = await saveImg(tempFilePath).catch(() => {
        closeLoading();
        tapLoading = false;
        uni.showToast({
            icon: "none",
            title: "保存图片失败",
        });
    });

    if(result){
        closeLoading();
        uni.showToast({
            icon: "none",
            title: "图片已保存至相册",
        });
        setTimeout(()=>{
            tapLoading = false;
        },1000)
    }

    // return new Promise((resolve, reject) => {
    //     uni.downloadFile({
    //         url: download_url,
    //         success(res) {
    //             const { tempFilePath } = res;
    //             reqTimes = 0;
    //             uni.saveImageToPhotosAlbum({
    //                 filePath: tempFilePath,
    //                 success() {
    //                     resolve(true);
    //                 },
    //                 fail(err) {
    //                     reject(error);
    //                 },
    //             });
    //         },

    //         fail(err) {
    //             if (reqTimes < 3) {
    //                 reqTimes += 1;
    //                 downLoadImg(download_url);
    //             } else {
    //                 reject(err);
    //             }
    //         },
    //     });
    // });
};

const select = () => {
    chooseImage({
        count: 1,
        success: (rst) => {
            // 设置url的值，显示控件
            imgurl.value = rst.tempFilePaths[0];
        },
    });
};

onLoad((option) => {

    if(option.userhead){
        try{
            const result = option.userhead;
            const index = result.lastIndexOf('.');
            const name = result.substring(0,index);
            const ext = result.substring(index,result.length);
            userhead.value = `${name}${ext}`;
            
        }catch(e){
            userhead.value = `/static/head.jpg`;
        }
    }else{
        userhead.value = `/static/head.jpg`;
    }


});
</script>

<style lang="scss" scoped>
.content {
    position: absolute;
    width: 750rpx;
    left: 0;
    right: 0;
    bottom: 0;
    background: #f5f5f5;
    padding: 20rpx;
    .box {
        width: 710rpx;
        padding: 20rpx;
        background: #fff;
        border-radius: 10rpx;
        .userhead {
            width: 100%;
        }
    }


    .control {
        position: fixed;
        width: 750rpx;
        left: 0;
        z-index:100;
        bottom:0;
        padding-bottom:constant(safe-area-inset-bottom);
        padding-bottom:env(safe-area-inset-bottom);

        .btn1 {
            position:relative;
             margin:0 auto;
            margin-bottom:20rpx;
        }

        .btn2 {
            position:relative;
             margin:0 auto;
            margin-bottom:20rpx;
        }
    }
}
</style>